const BaseController = require('../core/baseController')

//商品信息
class BannerController extends BaseController {
  //查询
  async fetchList() {
    const query = this.ctx.query
    try {
      const ret = await this.service.banner.findList(query)
      const all = await this.service.banner.fetchTotal()
      this.successForList(ret, query.pageSize, query.currentPage, all)
    } catch (e) {
      this.failure('查询失败')
    }
  }

  async fetchAll() {
    try {
      const ret = await this.service.banner.fetchAll();
      this.success(ret)
    } catch (e) {
      this.failure('查询失败', e)
    }
  }

  //新增
  async create() {
    const {ctx, service} = this
    let params = {
      name: ctx.request.body.name,
      icon: ctx.request.body.icon,
      sort: ctx.request.body.sort
    }
    try {
      await service.banner.add(params)
      const ret = await this.service.banner.findList({currentPage: 1, pageSize: 10})
      this.successForList(ret)
    } catch (e) {
      this.failure('新增失败')
    }


  }

//  更新接口
  async update() {
    const {
      ctx,
      service
    } = this
    let params = {
      _id: ctx.request.body._id,
      name: ctx.request.body.name,
      picture: ctx.request.body.picture,
      price: ctx.request.body.price,
      vipPrice: ctx.request.body.vipPrice,
      discount: ctx.request.body.discount,
      sort: ctx.request.body.sort,
    }
    try {
      await service.banner.update(params)
      const ret = await this.service.banner.findList({currentPage: 1, pageSize: 10})
      this.successForList(ret, 10, 1)
    } catch (e) {
      this.failure('更新失败')
    }


  }

  //删除
  async delete() {
    const {ctx, service} = this
    const _ids = ctx.request.body._ids.split(',')
    try {
      await service.banner.delete(_ids)
      const ret = await this.service.banner.findList({currentPage: 1, pageSize: 10})
      this.successForList(ret, 10, 1)
    } catch (e) {
      this.failure('删除失败')
    }

  }
}

module.exports = BannerController

